﻿<script setup lang="ts" name="CropperModal">
import { propTypes } from '@/utils/propTypes'
import { dataURLtoBlob } from '@/utils/file/helper'
import { FileApi } from '@/api/infra/resource/library'
const { t } = useI18n() // 国际化

const visible = ref(false)
let filename = ''

const props = defineProps({
  src: propTypes.string.def(''),
  title: propTypes.string.def(''),
  circled: propTypes.bool.def(true)
})

const emit = defineEmits(['uploadSuccess'])

const open = () => {
  visible.value = true
}

const close = () => {
  visible.value = false
}

// 子组件将方法暴露给父组件
defineExpose({ open, close })

const previewSource = ref(props.src || '')

const handleOk = async () => {
  const blob = dataURLtoBlob(previewSource.value)
  const file = new File([blob], filename)
  const res = await FileApi.upload({ file })
  emit('uploadSuccess', { url: res.info, name: res.name })
  close()
}

const fileChangeHandle = (obj) => {
  filename = obj.filename
  previewSource.value = obj.value
}
</script>

<template>
  <Dialog v-model="visible" :fullscreen="false" :title="title ? title : t('cropper', 'modalTitle')" appendToBody width="800px">
    <CropperWrap :srcValue="src" :circled="circled" @fileChange="fileChangeHandle" />
    <template #footer>
      <ElButton @click="close">{{ t('action', 'cancel') }}</ElButton>
      <ElButton type="primary" @click="handleOk">{{ t('cropper', 'confirmAndUpload') }}</ElButton>
    </template>
  </Dialog>
</template>

<style scoped lang="scss"></style>
